package com.item.mobile;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.dao.model.BFile;
import com.base.dialect.PaginationSupport;
import com.base.mobile.MobException;
import com.base.mobile.MobileInfo;
import com.base.mobile.server.annotation.Mobile;
import com.base.mobile.server.annotation.MobileMethod;
import com.base.service.BFileService;
import com.base.util.DateUtil;
import com.base.util.StringUtil;
import com.item.util.ApiUtil;
import com.item.util.ConstantResources;
import com.item.util.MyFileUtil;
import com.item.util.MailUtil;
import com.item.util.SimpleMailSender;
import com.item.dao.model.Essence;
import com.item.dao.model.EssenceAuthor;
import com.item.dao.model.EssenceAuthorCollect;
import com.item.dao.model.EssenceAuthorCollectExample;
import com.item.dao.model.EssenceAuthorCollectKey;
import com.item.dao.model.EssenceAuthorExample;
import com.item.dao.model.EssenceAuthorLock;
import com.item.dao.model.EssenceAuthorLockKey;
import com.item.dao.model.EssenceCollect;
import com.item.dao.model.EssenceCollectExample;
import com.item.dao.model.EssenceCourse;
import com.item.dao.model.EssenceCourseExample;
import com.item.dao.model.EssenceDownload;
import com.item.dao.model.EssenceDownloadExample;
import com.item.dao.model.EssenceExample;
import com.item.dao.model.EssenceNew;
import com.item.dao.model.EssenceNewExample;
import com.item.dao.model.EssenceReadState;
import com.item.dao.model.EssenceReadStateExample;
import com.item.dao.model.MediaFile;
import com.item.dao.model.MediaFileExample;
import com.item.dao.model.Note;
import com.item.dao.model.NoteAuthor;
import com.item.dao.model.NoteCollect;
import com.item.dao.model.NoteCollectKey;
import com.item.dao.model.NoteLock;
import com.item.dao.model.NoteLockKey;
import com.item.dao.model.Unread;
import com.item.dao.model.UnreadExample;
import com.item.daoEx.model.EssenceEx;
import com.item.service.EssenceAuthorCollectService;
import com.item.service.EssenceAuthorLockService;
import com.item.service.EssenceAuthorService;
import com.item.service.EssenceCollectService;
import com.item.service.EssenceCourseService;
import com.item.service.EssenceDownloadService;
import com.item.service.EssenceNewService;
import com.item.service.EssenceReadStateService;
import com.item.service.EssenceService;
import com.item.service.MediaFileService;
import com.item.service.NoteLockService;
import com.item.service.UnreadService;
import com.item.service.UserService;
import com.mobile.api.proto.MAppEssence.MEssence;
import com.mobile.api.proto.MAppEssence.MEssenceAuthor;
import com.mobile.api.proto.MAppEssence.MEssenceAuthorByDepart;
import com.mobile.api.proto.MAppEssence.MEssenceAuthorList;
import com.mobile.api.proto.MAppEssence.MEssenceAuthorListByDepart;
import com.mobile.api.proto.MAppEssence.MEssenceList;
import com.mobile.api.proto.MAppEssence.MEssenceMedia;
import com.mobile.api.proto.MAppEssence.MEssenceMediaList;
import com.mobile.api.proto.MAppEssence.MEssenceSim;
import com.mobile.api.proto.MAppNote.MNoteBook;
import com.mobile.api.proto.MSystem.MRet;
import com.mobile.api.proto.MSystem.MRecomendKeys;
import static com.item.mobile.MobileUtil.checkParam;

@Component
@Mobile
public class MAppEssence {

	@Autowired
	private EssenceService essenceService;
	
	@Autowired
	private EssenceNewService newEssenceService;
	
	@Autowired
	private EssenceCollectService collectService;
	
	@Autowired
	private EssenceDownloadService downloadService;
	
	@Autowired
	private UnreadService unreadService;
	
	@Autowired
	private MediaFileService mediaFileService;
	
	@Autowired
	private EssenceAuthorService  authorService;
	@Autowired
	private EssenceAuthorCollectService  authorCollectService;
	@Autowired
	private EssenceAuthorLockService essenceLockService;
	@Autowired
	private EssenceCourseService courseService;
	@Autowired
	private EssenceReadStateService readService;
	
	
	static  Logger log = Logger.getLogger(MAppEssence.class);
	
	/**
	 * V2.0
	 * @param mobileInfo
	 * @param type
	 * @param key
	 * @param page
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceAuthors",isLogin=true,isPage=false)
	public MEssenceAuthorList.Builder authorList(MobileInfo mobileInfo,Integer type,String key,Integer page,Integer limit)throws Exception{
		checkParam(type, "type");
		if(page == null)
			page = 1;
		if(limit == null)
			limit = 10;
		//清空名师的未读
		Unread read = new Unread();
		read.setUserid(mobileInfo.getUserid());
		read.setModule2(0);
		read.setModifyTime(new Date());
		unreadService.updateByPrimaryKeySelective(read);
		//再去获取名师列表
		MEssenceAuthorList.Builder ret = MEssenceAuthorList.newBuilder();
		EssenceAuthorExample eaex = new EssenceAuthorExample();
		EssenceAuthorExample.Criteria criteria = eaex.createCriteria();
		criteria.andSubjectLike("%" + type + "%").andIsLockEqualTo(1);
//		criteria.andTypeLessThan(3);
		if(StringUtils.isNotBlank(key)){
			criteria.andNameLike("%" + key + "%");
		}
		eaex.setOrderByClause("type ASC,top DESC,last_update_time DESC");
		PaginationSupport.setContext(page, limit, null);
		List<EssenceAuthor> lists = authorService.selectByExample(eaex);
		int total = PaginationSupport.getContext().getTotalCount();
		for(EssenceAuthor item : lists){
			MEssenceAuthor.Builder tmp = fillAuthorData(mobileInfo, item,0,type);
			if(tmp != null){
				ret.addAuthor(tmp);
			}
		}
		//获得下一页的URL
		Map<String,String> params = ApiUtil.createParamMaps();
		if(StringUtils.isNotBlank(key)){
			params.put("key", key);
		}
		if(type != null){
			params.put("type", type+"");
		}
		ret.setNext(ApiUtil.getNextPageUrl("MEssenceAuthors", mobileInfo, total ,page, limit,params));
		return ret;
	}
	
	/**
	 * V2.0
	 * @param mobileInfo
	 * @param type
	 * @param id
	 * @param page
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceAuthorsByDepart",isLogin=true,isPage=false)
	public MEssenceAuthorListByDepart.Builder authorListByDepart(MobileInfo mobileInfo,Integer type,String id,Integer page,Integer limit)throws Exception{
		checkParam(type, "type");
		checkParam(id, "id");
		if(page == null)
			page = 1;
		if(limit == null)
			limit = 10;
		MEssenceAuthorListByDepart.Builder ret = MEssenceAuthorListByDepart.newBuilder();
		//首先拿到当前科目所有有教师的班级列表
		EssenceCourseExample ecex = new EssenceCourseExample();
		ecex.createCriteria().andSubjectEqualTo(type+"").andHasAuthorEqualTo(1);
		PaginationSupport.setContext(page, limit, null);
		ecex.setOrderByClause("top DESC");
		Map<String,String> map = ApiUtil.createParamMaps();
		map.put("depart", '%'+id+'%');
		map.put("type", type+"");
		List<EssenceCourse> lists = courseService.getEssenceCourseByDeaprt(map);
		for(EssenceCourse course : lists){
			MEssenceAuthorByDepart.Builder retByDepart = MEssenceAuthorByDepart.newBuilder();
			retByDepart.setTitle(course.getName());
			EssenceAuthorExample eaex = new EssenceAuthorExample();
			eaex.createCriteria().andCoursesLike("%"+course.getName() + "%").andSubjectEqualTo(type+"").andTypeEqualTo(1).andBelongidLike("%" + id + "%");
			List<EssenceAuthor> authors = authorService.selectByExample(eaex);
			if(authors != null && authors.size() > 0){
				for(EssenceAuthor author : authors){
					retByDepart.addBooks(fillAuthorData(mobileInfo, author, 1,type));
				}
				ret.addNotes(retByDepart);
			}
		}
		//获得下一页的URL
		Map<String,String> params = ApiUtil.createParamMaps();
		if(StringUtils.isNotBlank(id)){
			params.put("id", id);
			params.put("type", type+"");
		}
		ret.setNext(ApiUtil.getNextPageUrl("MEssenceAuthorsByDepart", mobileInfo, PaginationSupport.getContext().getTotalCount() ,page, limit,params));
		return ret;
	}
	
	/**
	 * V2.0
	 * @param mobileInfo
	 * @param id
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceAuthorCollect", isLogin = true)
	public MRet.Builder collectAuthor(MobileInfo mobileInfo,String id,Integer type) throws Exception {
		if(type == null){
			type = 1;
		}
		EssenceAuthorCollectKey key = new EssenceAuthorCollectKey();
		key.setPid(id);
		key.setUserid(mobileInfo.getUserid());
		EssenceAuthorCollect collect = authorCollectService.selectByPrimaryKey(key);
		if(collect == null){
			collect = new EssenceAuthorCollect();
			collect.setPid(id);
			collect.setUserid(mobileInfo.getUserid());
			collect.setType(1);
			collect.setCreateTime(new Date());
			collect.setModifyTime(collect.getCreateTime());
			authorCollectService.insert(collect);
		}else{
			collect.setType(type);
			collect.setModifyTime(new Date());
			authorCollectService.updateByPrimaryKey(collect);
		}
		//再更新收藏数量
		EssenceAuthor author = authorService.selectByPrimaryKey(id);
		if(author == null){
			throw new MobException("id");
		}
		if(type == 1){
			author.setCollectCount(author.getCollectCount() + 1);
		}else{
			author.setCollectCount(author.getCollectCount() - 1);
		}
		authorService.updateByPrimaryKeySelective(author);
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(1);
		return ret;
	}
	
	/**
	 * V2.0
	 * @param mobileInfo
	 * @param author
	 * @param page
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceListNew",isLogin=false,isPage=false)
	public MEssenceList.Builder essencesNew(MobileInfo mobileInfo, String id,Integer page, Integer limit) throws Exception {
		checkParam(id, "authorId");
		if(page == null)
			page = 1;
		if(limit == null)
			limit = 10;
		MEssenceList.Builder ret = MEssenceList.newBuilder();
		EssenceNewExample enex = new EssenceNewExample();
		enex.createCriteria().andAuthorEqualTo(id);
		enex.setOrderByClause("is_over DESC,top DESC,create_time DESC");
		
		PaginationSupport.setContext(page, limit, null);
		List<EssenceNew> lists = newEssenceService.selectByExample(enex);
		
		for(EssenceNew item : lists){
			ret.addEssence(assembleEssenNew(item,mobileInfo));
			
		}
		//获得下一页的URL
		Map<String,String> params = ApiUtil.createParamMaps();
		if(StringUtils.isNotBlank(id)){
			params.put("id", id);
		}
		//是否收藏过了
		EssenceAuthorCollectExample eacex = new EssenceAuthorCollectExample();
		eacex.createCriteria().andUseridEqualTo(mobileInfo.getUserid()).andTypeEqualTo(1).andPidEqualTo(id);
		ret.setHasCollect(authorCollectService.countByExample(eacex));
		ret.setNext(ApiUtil.getNextPageUrl("MEssenceListNew", mobileInfo, PaginationSupport.getContext().getTotalCount() ,page, limit,params));
		return ret;
	}
	
	/**
	 * V2.0   获取课程下的所有资源文件
	 * @param mobileInfo
	 * @param id
	 * @param page
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceDetailList",isLogin=false,isPage=false)
	public MEssenceMediaList.Builder essencesList(MobileInfo mobileInfo, String id,Integer page, Integer limit) throws Exception {
		checkParam(id, "id");
		if(page == null)
			page = 1;
		if(limit == null)
			limit = 10;
		//首先清空未读数目  ！！重要
		EssenceReadStateExample ersex = new EssenceReadStateExample();
		ersex.createCriteria().andEssenceIdEqualTo(id).andUseridEqualTo(mobileInfo.getUserid());
		EssenceReadState state = new EssenceReadState();
		state.setCount(0);
		readService.updateByExampleSelective(state, ersex);
		//首先增加浏览次数
		EssenceNew essence = newEssenceService.selectByPrimaryKey(id);
		if(essence == null){
			throw new MobException(MEnumError.ESSENCE_NOT_EXISTS);
		}else{
			essence.setBrowseTimes(essence.getBrowseTimes() + 1);
			newEssenceService.updateByPrimaryKeySelective(essence);
		}
		//再去拿文件
		MEssenceMediaList.Builder ret = MEssenceMediaList.newBuilder();
		MediaFileExample mex = new MediaFileExample();
		mex.createCriteria().andEssenceIdEqualTo(id);
		mex.setOrderByClause("name ASC");
		PaginationSupport.setContext(page, limit, null);
		List<MediaFile> lists = mediaFileService.selectByExample(mex);
		for(MediaFile item : lists){
			MEssenceMedia.Builder media = fillMediaData(mobileInfo, item);
			if(media != null){
				ret.addMedias(media);
			}
		}
		Map<String,String> params = ApiUtil.createParamMaps();
		if(StringUtils.isNotBlank(id)){
			params.put("id", id);
		}
		ret.setNext(ApiUtil.getNextPageUrl("MEssenceDetailList", mobileInfo, PaginationSupport.getContext().getTotalCount() ,page, limit,params));
		return ret;
	}
	
	/**
	 * 资源文件发送邮箱V2.0
	 * @param mobileInfo
	 * @param id
	 * @param email
	 * @param resid
	 * @param isShared
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MMediaFileEmail",isLogin=true,isPage=false)
	public MRet.Builder mediaEmail(MobileInfo mobileInfo, String id,final String email) throws Exception {
		checkParam(id, "id");
		checkParam(email, "email");
		
		EssenceDownloadExample edex = new EssenceDownloadExample();
		edex.createCriteria().andUseridEqualTo(mobileInfo.getUserid()).andEssenceIdEqualTo(id);
		//
		List<EssenceDownload> lists = downloadService.selectByExample(edex);
		//说明还没有下载记录
		if(lists == null || lists.size() < 1){
			EssenceDownload download = new EssenceDownload();
			download.setCount(1);
			download.setEssenceId(id);
			download.setUserid(mobileInfo.getUserid());
			download.setCreateTime(new Date());
			download.setModifyTime(download.getCreateTime());
			downloadService.insert(download);
		}else{
			EssenceDownload download = lists.get(0);
			download.setCount(download.getCount() + 1);
			downloadService.updateByPrimaryKeySelective(download);
		}
		//再更新精华的下载次数
		MediaFile file = new MediaFile();
		file.setFileId(id);
		mediaFileService.addDownloadTimes(file);
		//发送邮件
		MRet.Builder ret = MRet.newBuilder();
		final MediaFile essen = mediaFileService.selectByPrimaryKey(id);
		new Thread(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub
				StringBuilder sb = new StringBuilder();
				sb.append(appendEmaiContent(essen.getFileId(), null));
//				sb.append(appendEmaiContent(essen.getMediaIds(), essen));
//				SimpleMailSender sender = com.item.util.SimpleMailSender.create(email);
				MailUtil.sendMail(email, essen.getName() + "下载", sb.toString());
			}
		}).start();
//		System.out.println(file.getFilePath());
		ret.setCode(1);
		ret.setMsg("发送成功");
		return ret;
	}
	
	
	/**
	 * 获取精华列表    
	 * @param mobileInfo
	 * @param type
	 * @param keyword  keyword用于搜索精华时
	 * @param page
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceList",isLogin=false,isPage=true)
	public MEssenceList.Builder essences(MobileInfo mobileInfo, String author,String key, Integer page, Integer limit,Integer subType,Integer resType) throws Exception {
//		if(page == null || limit == null){
//			throw new MobException("缺少分页参数");
//		}
//		System.out.println(type);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userid", mobileInfo.getUserid());
		if(StringUtils.isNotBlank(author)){
			map.put("author", author);
		}
		MEssenceList.Builder ret = MEssenceList.newBuilder();
		EssenceExample eex = new EssenceExample();
		PaginationSupport.setContext(page, limit, null);
		eex.setOrderByClause("top DESC, create_time DESC");
		EssenceExample.Criteria cr = eex.createCriteria();
		StringBuilder sb = new StringBuilder();
		if(StringUtils.isNotBlank(key)){
			String[] keys = key.split(" ");
			for(String k : keys){
				sb.append("%").append(k).append("%");
			}
			if(StringUtils.isNotBlank(key)){
				map.put("key", sb.toString());
			}
			subType = null;
		}else{
			if(subType != null){
				map.put("subType", subType);
//				subType = 1;
			}
		}
//		cr.andSubTypeEqualTo(subType);
		if(resType != null){
			map.put("resType", resType);
		}
		List<EssenceEx> lists = essenceService.getEssenceEx(map);
//		System.out.println(lists.size());
		for(EssenceEx item : lists){
			MEssence.Builder essen = assembleEssenEx(item, 1);
			ret.addEssence(essen);
		}
		return ret;
	}
	
	
	/**
	 * 获取精华帖子的详情
	 * @param mobileInfo
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceDetail",isLogin=false,isPage=false)
	public MEssence.Builder essence(MobileInfo mobileInfo, String id) throws Exception {
		if(StringUtils.isBlank(id)){
			throw new MobException("id");
		}
		Map<String,String> map = new HashMap<String,String>();
		map.put("id", id);
		map.put("userid", mobileInfo.getUserid());
		List<EssenceEx> lists = essenceService.getEssenceEx(map);
		if(lists == null || lists.size() < 1){
			
		}
		final EssenceEx item = lists.get(0);
		MEssence.Builder ret = assembleEssen(item, 1);
		//这两个是需要附加的字段
		ret.setIsCollected(item.getIsCollect());
		ret.setIsDownloaded(item.getIsDownload());
		//新开线程去更新浏览数目
		new Thread(new Runnable(){
			public void run(){
				Essence es = new Essence();
				es.setId(item.getId());
				es.setBrowseTimes(item.getBrowseTimes() + 1);
				essenceService.updateByPrimaryKeySelective(es);
			}
		}).start();
		return ret;
	}
	
	/**
	 * 收藏与取消收藏  type为1收藏，为0取消收藏
	 * @param mobileInfo
	 * @param id
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEssenceCollect",isLogin=true,isPage=false)
	public MRet.Builder essenceCollect(MobileInfo mobileInfo, String id,String type) throws Exception {
		checkParam(id, "id");
		checkParam(type,"type");
		String[] ids = id.split(",");
		for(String pid :ids){
			EssenceCollectExample eclex = new EssenceCollectExample();
			eclex.createCriteria().andUseridEqualTo(mobileInfo.getUserid()).andEssenceIdEqualTo(pid);
			List<EssenceCollect> collects = collectService.selectByExample(eclex);
			if(collects != null && collects.size() > 0){
				EssenceCollect collect = collects.get(0);
				collect.setStatus(type);
				collect.setModifyTime(new Date());
				collectService.updateByExampleSelective(collect, eclex);
			}else{
				EssenceCollect collect = new EssenceCollect();
				collect.setEssenceId(pid);
				collect.setUserid(mobileInfo.getUserid());
				collect.setCreateTime(new Date());
				collect.setModifyTime(collect.getCreateTime());
				collect.setStatus("1");
				collectService.insert(collect);
			}
		}
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(1);
		ret.setMsg("操作成功");
		return ret;
	}
	
	@MobileMethod(methodno = "MEssenceDownload",isLogin=true,isPage=false)
	public MRet.Builder essenceDownload(MobileInfo mobileInfo, String id,final String email,String resid,Integer isShared) throws Exception {
		checkParam(id, "id");
		checkParam(email, "email");
		//checkParam(resid, "resid");
		checkParam(isShared, "isShared");
		
		
		EssenceDownloadExample edex = new EssenceDownloadExample();
		edex.createCriteria().andUseridEqualTo(mobileInfo.getUserid()).andEssenceIdEqualTo(id);
		//
		List<EssenceDownload> lists = downloadService.selectByExample(edex);
		//说明还没有下载记录
		if(lists == null || lists.size() < 1){
			EssenceDownload download = new EssenceDownload();
			download.setCount(1);
			download.setEssenceId(id);
			download.setUserid(mobileInfo.getUserid());
			download.setCreateTime(new Date());
			download.setModifyTime(download.getCreateTime());
			download.setIsShared(isShared);
			downloadService.insert(download);
		}else{
			EssenceDownload download = lists.get(0);
			download.setCount(download.getCount() + 1);
			downloadService.updateByPrimaryKeySelective(download);
		}
		//再更新精华的下载次数
		Essence essen1 = new Essence();
		essen1.setId(id);
		essenceService.addEssenceDownload(essen1);
		//发送邮件
		MRet.Builder ret = MRet.newBuilder();
		final Essence essen = essenceService.selectByPrimaryKey(id);
		new Thread(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub
				StringBuilder sb = new StringBuilder();
				sb.append(appendEmaiContent(essen.getResid(), essen));
				sb.append(appendEmaiContent(essen.getMediaIds(), essen));
//				SimpleMailSender sender = com.item.util.SimpleMailSender.create(email);
				MailUtil.sendMail(email, essen.getTitle() + "下载", sb.toString());
			}
		}).start();
//		System.out.println(file.getFilePath());
		ret.setCode(1);
		ret.setMsg("发送成功");
		return ret;
	}
	
	@MobileMethod(methodno = "MMyEssences",isLogin=true,isPage=true)
	public MEssenceList.Builder myessence(MobileInfo mobileInfo, Integer resType,Integer page,Integer limit) throws Exception {
		MEssenceList.Builder ret = MEssenceList.newBuilder();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userid", mobileInfo.getUserid());
		if(resType != null){
			map.put("resType", resType);
		}
		PaginationSupport.setContext(page, limit, null);
		List<Essence> lists = essenceService.getMyEssence(map);
		for(Essence item : lists){
			MEssence.Builder essen = assembleEssen(item, 1);
			ret.addEssence(essen);
		}
		return ret;
	}
	
	@MobileMethod(methodno = "MRecommendKeys",isLogin=false,isPage=false)
    public MRecomendKeys.Builder getRecommendKeys(MobileInfo mobileInfo, String key){
		MRecomendKeys.Builder ret = MRecomendKeys.newBuilder();
		Map<String,String> map = new HashMap<String, String>();
		map.put("key", key + "%");
		PaginationSupport.setContext(1, 5, null);
		List<String> lists = essenceService.getRecomendKeys(map);
		for(String str : lists){
			ret.addKey(str);
		}
		return ret;
	}
	
	/**
	 * 笔记分享之后的回调请求
	 * @param mobileInfo
	 * @param id
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MEsseceShare", isLogin = true)
	public MRet.Builder share(MobileInfo mobileInfo,String id) throws Exception {
		EssenceAuthorLockKey key = new EssenceAuthorLockKey();
		key.setPid(id);
		key.setUserid(mobileInfo.getUserid());
		if(essenceLockService.selectByPrimaryKey(key)==null){
			EssenceAuthorLock lock = new EssenceAuthorLock();
			lock.setPid(key.getPid());
			lock.setUserid(key.getUserid());
			lock.setCreateTime(new Date());
			essenceLockService.insert(lock);
		}		
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(1);
		return ret;
	}
	
	public MEssenceMedia.Builder fillMediaData(MobileInfo mobileInfo,MediaFile file)throws Exception{
		MEssenceMedia.Builder ret = MEssenceMedia.newBuilder();
		ret.setName(file.getName());
		ret.setId(file.getFileId());
		ret.setBroseCount(file.getBrowseCount());
		ret.setDate(DateUtil.dateToStr(file.getFileCreatetime(), "yyyy-MM-dd"));
		ret.setFileSize(Integer.valueOf(file.getFileSize().toString()));
		if(file.getFileName().toLowerCase().endsWith("pdf")){
				ret.setType(1);
				ret.setUrl(String.format(ConstantResources.PDFURL, ConstantResources.OSS_OUT_WEB_URL+"/"+file.getFilePath()));
		}else if(file.getFileName().toLowerCase().endsWith("mp3")){
			   ret.setType(2);
			   ret.setUrl(String.format("%s?id=%s&t=%d", ConstantResources.ESSENCEURL,file.getFileId(),System.currentTimeMillis()));
			
		}else if(file.getFileName().toLowerCase().endsWith("mp4")){
			  ret.setType(3);
			  ret.setUrl(String.format("%s?id=%s&t=%d", ConstantResources.ESSENCEURL,file.getFileId(),System.currentTimeMillis()));
		}
		if(StringUtils.isNotBlank(ret.getUrl())){
			ret.setDownloadUrl(ConstantResources.OSS_OUT_WEB_URL + URLEncoder.encode(file.getFilePath(),"UTF-8"));
			return ret;
		}
		
		return null;
	}
	
	//type 0为名师列表  1为按机构的名师
	public MEssenceAuthor.Builder fillAuthorData(MobileInfo mobileInfo,EssenceAuthor author,int type,int subject){
		MEssenceAuthor.Builder ret = MEssenceAuthor.newBuilder();
		ret.setId(author.getId());
		ret.setName(author.getName());
		ret.setAreas(author.getAreas());
		ret.setDesc(author.getDescription());
		ret.setSlogan(author.getSlogan());
		ret.setCollectCount(author.getCollectCount()+"");
		ret.setCover(author.getHeadimg());
		ret.setSubject(subject);
		ret.setType(author.getType());
		if(type == 0){
			//那最新的2-3个视频
			EssenceNewExample eex = new EssenceNewExample();
			eex.setOrderByClause("create_time DESC");
			if(author.getType() == 1){
				eex.createCriteria().andAuthorEqualTo(author.getId()).andIsDigestEqualTo(1);
			}else{
				eex.createCriteria().andBelongLike("%"+author.getId()+"%").andIsDigestEqualTo(1);
			}
			PaginationSupport.setContext(1, 3, null);
			StringBuilder sb = new StringBuilder();
			List<EssenceNew> lists = newEssenceService.selectByExample(eex);
			if(lists == null || lists.size() < 1){
				return null;
			}
			for(EssenceNew item : lists){
				sb.append(item.getDisplayName()).append(";");
			}
			ret.setEssencesStr(sb.toString().substring(0, sb.length()));
			//是否收藏过了
			EssenceAuthorCollectExample eacex = new EssenceAuthorCollectExample();
			eacex.createCriteria().andUseridEqualTo(mobileInfo.getUserid()).andTypeEqualTo(1).andPidEqualTo(author.getId());
			ret.setHasCollect(authorCollectService.countByExample(eacex));
		}
		
		if(author.getType() == 1){
			ret.setBelong(author.getBelong().split(";")[0]);
			//到阅读状态表中查询未读数目
			Map<String,String> map = ApiUtil.createParamMaps();
			map.put("author", author.getId());
			map.put("userid", mobileInfo.getUserid());
			ret.setNewCount(readService.getUnReadCount(map));
		}
		ret.setShareUrl(ConstantResources.ESSENCEAUTHORURL);
		
		
		
		return ret;
	}
	
	public MEssence.Builder assembleEssenNew(EssenceNew item,MobileInfo mobileInfo){
		MEssence.Builder ret = MEssence.newBuilder();
		//设置必须的信息
		ret.setId(item.getId());
		ret.setTitle(item.getDisplayName());
		ret.setSource(item.getSource());
		ret.setBrowseCount(item.getBrowseTimes());
		ret.setBrowseTimes(item.getBrowseTimes());
		ret.setShareUrl(String.format("%s?teacherId=%s&t=%d", ConstantResources.ESSENCEAUTHORURL,item.getAuthor(),System.currentTimeMillis()));
		if(item.getIsOver() == 1){
			ret.setStatus(1);
		}else{
			EssenceReadStateExample ersex = new EssenceReadStateExample();
			ersex.createCriteria().andEssenceIdEqualTo(item.getId()).andUseridEqualTo(mobileInfo.getUserid());
			List<EssenceReadState> lists = readService.selectByExample(ersex);
			if(lists == null || lists.size() < 1){
				EssenceReadState state = new EssenceReadState();
				state.setAuthorId(item.getAuthor());
				state.setCount(0);
				state.setCreateTime(new Date());
				state.setEssenceId(item.getId());
				state.setUserid(mobileInfo.getUserid());
				readService.insert(state);
				ret.setStatus(0);
			}else{
				EssenceReadState state = lists.get(0);
				if(state.getCount() > 0){
					ret.setStatus(2);
				}else{
					ret.setStatus(0);
				}
			}
		}
		//需要判断下这个用户有没有解锁
		if(item.getIsLocked() == 1){
			ret.setIsLocked(checkUnlockde(item.getId(), mobileInfo.getUserid()));
		}else{
			ret.setIsLocked(0);
		}
		return ret;
	}
	
	public MEssence.Builder assembleEssenEx(EssenceEx item, int type){
		MEssence.Builder ret = assembleEssen(item,type);
		ret.setIsCollected(item.getIsCollect());
		ret.setIsDownloaded(item.getIsDownload());
		return ret;
	}
	
	
	
	/**
	 * 组装精华的数据 
	 * @param item
	 * @param type 为0时只组装我的收藏了的数据，为1时组装所有数据
	 * @return
	 */
	public MEssence.Builder assembleEssen(Essence item, int type){
		MEssence.Builder ret = MEssence.newBuilder();
		//设置必须的信息
		ret.setId(item.getId());
		ret.setTitle(item.getTitle());
		ret.setSource(item.getSource());
		ret.setTime(DateUtil.dateToStr(item.getCreateTime(), "yyyy-MM-dd"));
		ret.setType(item.getType());  //type目前暂时没用
		ret.setNeedShare(item.getIsAd());
		ret.setSubjectType(item.getSubType());
		ret.setSubjectName(item.getSubName());
		ret.setBrowseTimes(item.getBrowseTimes());
		ret.setShareUrl(String.format("%s?id=%s&t=%d", item.getShareUrl(),item.getId(),System.currentTimeMillis()));
		//设置是否有资源文件，如果没有说明为资讯；资讯需要设置url
		ret.setHasDownload(StringUtils.isBlank(item.getResid()) && StringUtils.isBlank(item.getMediaIds()) ? 0 : 1);
		if(ret.getHasDownload() == 1){
			ret.setResType(item.getResType());
			ret.setResSize(MyFileUtil.getFileSize(item.getResSize()));
			ret.setDownloadTimes(item.getDownloadTimes());
			//resid表示的文档资源，无需在线观看
			ret.setResid(StringUtil.emptyIfBlank(item.getResid()));
			if(StringUtils.isNotBlank(item.getMediaIds()) || StringUtils.isNotBlank(item.getResid())){
				String[] medias = null;
				if(item.getResType() == 2){
					//如果是文档的话，那么直接给它文档的URL
					medias = item.getResid().split(",");
				}else{
					medias = item.getMediaIds().split(",");
				}
				for(int i = 0 ; i < medias.length ; i++){
					MEssenceMedia.Builder mediaRet = MEssenceMedia.newBuilder();
					MediaFile file = mediaFileService.selectByPrimaryKey(medias[i]);
					mediaRet.setName(file.getName());
					mediaRet.setFileName(file.getFileName());
					//2的话是文档
					if(item.getResType() ==2){
						if(file.getFileName().toLowerCase().endsWith("pdf"))
							mediaRet.setType(2);
							mediaRet.setUrl(String.format(ConstantResources.PDFURL, ConstantResources.OSS_BASE_URL+"/"+file.getFilePath()));
					}else{
						if(file.getFileName().toLowerCase().endsWith("mp4")||file.getFileName().toLowerCase().endsWith("mp3")){
							mediaRet.setType(1);
							mediaRet.setUrl(String.format("%s?id=%s&t=%d", ConstantResources.ESSENCEURL,file.getFileId(),System.currentTimeMillis()));
						}
					}
					if(StringUtils.isNotBlank(mediaRet.getUrl())){
						mediaRet.setNumber(i+1);
						mediaRet.setDownloadUrl(ConstantResources.OSS_BASE_URL + file.getFilePath());
						ret.addMedia(mediaRet);
					}
				}
			}
		}else{
			ret.setUrl(item.getUrl());
		}
		return ret;
	}
	
	public String appendEmaiContent(String ids,Essence essen){
		String[] temp = ids.split(",");
		StringBuilder sb = new StringBuilder();
		for(String str : temp){
			MediaFile file = mediaFileService.selectByPrimaryKey(str);
			if(file != null){
				sb.append(String.format(ConstantResources.DOWNLOADEMAILCONTENT, file.getFileName().split("\\.")[0], ConstantResources.OSS_OUT_WEB_URL+file.getFilePath()));
				sb.append("<br/>");
			}
		}
		return sb.toString();
	}
	
	public int checkUnlockde(String noteId, String userid){
		int result = 1;
		EssenceAuthorLockKey key = new EssenceAuthorLockKey();
		key.setPid(noteId);
		key.setUserid(userid);
		//说明该笔记已经对该用户解锁了
		if(essenceLockService.selectByPrimaryKey(key) != null){
			result = 0;
		}
		return result;
	}
	
	
	
	
}
